import {Component, OnInit, ElementRef, ViewChild} from '@angular/core';
import {ActualWindPower} from '../../../entity/actual-wind-power.model';
import {PowerLoss} from '../../../entity/power-loss.model';
import {ActualWindPowerService} from '../../../service/actual-wind-power.service';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {List} from 'linqts';
import {seriesData} from './compare-echarts/echarts.model';
import {WindPowers} from '../../../entity/wind-powers.model';
import {FarmCategoryEnum} from '../../common/device-tag-selector/farm-category.enum';
import {DeviceCategoryEnum} from '../../common/device-tag-selector/device-category.enum';
import {Device} from '../../../entity/device.model';
import {NzMessageService} from 'ng-zorro-antd';
import {ApplicationService} from '../../../service/application.service';
import {DeviceGroupCategoryEnum} from '../../common/device-tag-selector/device-selector/device-selector.component';

@Component({
  selector: 'app-power-compare',
  templateUrl: './power-compare.component.html',
  styleUrls: ['./power-compare.component.css']
})
export class PowerCompareComponent implements OnInit {
  public farmCategory: FarmCategoryEnum = FarmCategoryEnum.winfarm;
  public deviceCategory: DeviceCategoryEnum[] = [DeviceCategoryEnum.turbine];
  // public years: string[] = ["2017", "2016", "2015", "2014", "2013", "2012", "2011", "2010"];
  public years: string[] = [];
  public currentYear: string = (new Date().getFullYear()).toString();
  // public months: string[] = ["12", "11", "10", "9", "8", "7", "6", "5", "4", "3", "2", "1"];
  public months: string[] = [];
  public currentMonth: string = (new Date().getMonth()).toString();
  public quarters: number[] = [];
  public currentQuarter: number = Math.floor((new Date().getMonth() % 3 == 0 ? (new Date().getMonth() / 3) : (new Date().getMonth() / 3 + 1))) - 1;

  /**
   * 数据源服务
   *
   * @private
   * @type {DataSourceService}
   * @memberof PowerCompareComponent
   */
  private dataSource: DataSourceService;

  //返回数据
  public actualWindPowerDataYear: ActualWindPower[] = [];
  private originalActualYear: ActualWindPower[] = [];
  private powerLossDataYear: PowerLoss[] = [];
  private originalPowerLossYear: PowerLoss[] = [];
  public compareDataHighYear: PowerLoss[] = [];
  public compareDataLowYear: PowerLoss[] = [];

  public actualWindPowerDataMonth: ActualWindPower[] = [];
  private originalActualMonth: ActualWindPower[] = [];
  private powerLossDataMonth: PowerLoss[] = [];
  private originalPowerLossMonth: PowerLoss[] = [];
  public compareDataHighMonth: PowerLoss[] = [];
  public compareDataLowMonth: PowerLoss[] = [];

  public actualWindPowerDataQuarter: ActualWindPower[] = [];
  private originalActualQuarter: ActualWindPower[] = [];
  private powerLossDataQuarter: PowerLoss[] = [];
  private originalPowerLossQuarter: PowerLoss[] = [];
  public compareDataHighQuarter: PowerLoss[] = [];
  public compareDataLowQuarter: PowerLoss[] = [];

  //型号设计曲线数据 年
  private modelWindPowerData: WindPowers[] = [];
  private originalModelWindPower: WindPowers[] = [];

  //型号设计曲线数据 季度
  private modelWindPowerDataQuarter: WindPowers[] = [];
  private originalModelWindPowerQuarter: WindPowers[] = [];

  //型号设计曲线数据 月
  private modelWindPowerDataMonth: WindPowers[] = [];
  private originalModelWindPowerMonth: WindPowers[] = [];

  //EPLostPerformTotalPer > 10%, 比较参数
  private compareParamHigh: number = -10;
  private compareParamLow: number = 10;

  /**
   * 风机id集合,时间类型
   *
   * @type @memberof PowerCompareComponent
   */
  private turbineIds: number[] = [];
  private dateType: number;

  /**
   * 生成导出表格数据
   *
   * @type @memberof PowerCompareComponent
   */
    // public windPowersTabData: ActualWindPower[] = [];
  public windPowersTabData: any[] = [];

  /**
   * 当前选中下标
   *
   * @type {number}@memberof PowerCompareComponent
   */
  active: number = 0;

  /**
   * 图例(年)
   *
   * @type {object}@memberof PowerCompareComponent
   */
  yearLegend: {};

  /**
   * echart series(年)
   *
   * @type {any[]}@memberof PowerCompareComponent
   */
  yearSeries: seriesData[] = [];

  /**
   * 图例(季度)
   *
   * @type {object}@memberof PowerCompareComponent
   */
  quarterLegend: {};

  /**
   * echart series(季度)
   *
   * @type {any[]}@memberof PowerCompareComponent
   */
  quarterSeries: seriesData[] = [];

  /**
   * 图例(月)
   *
   * @type {object}@memberof PowerCompareComponent
   */
  monthLegend: {};

  /**
   * echart series(月)
   *
   * @type {any[]}@memberof PowerCompareComponent
   */
  monthSeries: seriesData[] = [];

  public maxPower: number;
  /**
   *设备选择最大数量
   *
   * @type {number}
   * @memberof PowerCompareComponent
   */
  deviceCountLimit = 20;
  /**
   *刚进页面是默认选择风机数量
   *默认:null 不做限制
   * 0不选择
   * @memberof PowerCompareComponent
   */
  defaultChooseDeviceCount;
  deviceGroupCategory: DeviceGroupCategoryEnum = DeviceGroupCategoryEnum.byModel;


  constructor(
    private actualWindPowerService: ActualWindPowerService,
    private _message: NzMessageService,
    private application: ApplicationService,
  ) {
    console.log(this.currentQuarter)
    for (let i = 0; i < 10; i++) {
      this.years.push((new Date().getFullYear() - i).toString())
    }
    for (let j = 1; j < new Date().getMonth() + 1; j++) {
      this.months.push(j.toString())
    }

    for (let k = 1; k <= this.currentQuarter; k++) {
      this.quarters.push(k);
    }


  }

  ngOnInit() {
    if (this.application.currentMenuParams && this.application.currentMenuParams['deviceCountLimit']) {
      this.deviceCountLimit = Number(this.application.currentMenuParams['deviceCountLimit'].paramValue);
    } else {
      this.deviceCountLimit = 20;
    }
    ;
    if (this.application.currentMenuParams && this.application.currentMenuParams['defaultChooseDeviceCount']) {
      this.defaultChooseDeviceCount = Number(this.application.currentMenuParams['defaultChooseDeviceCount'].paramValue);
    } else {
      this.defaultChooseDeviceCount = 1;
    }
  }

  public onChangeYear(event) {
    this.currentYear = event;
    if (Number(this.currentYear) != new Date().getFullYear()) {
      this.months = ['12', '11', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1'];
      this.quarters = [1, 2, 3, 4];
      this.currentMonth = this.months[0];
      this.currentQuarter = this.quarters[0];
    } else {
      this.months = [];
      this.quarters = [];
      this.currentMonth = (new Date().getMonth()).toString();
      this.currentQuarter = Math.floor((new Date().getMonth() % 3 == 0 ? (new Date().getMonth() / 3) : (new Date().getMonth() / 3 + 1))) - 1;
      for (let j = 1; j < new Date().getMonth() + 1; j++) {
        this.months.push(j.toString())
      }
      for (let k = 1; k <= this.currentQuarter; k++) {
        this.quarters.push(k);
      }
    }

  }

  public onChangeQuarter(event) {
    this.currentQuarter = event;
  }

  public onChangeMonth(event) {
    this.currentMonth = event;
  }

  /**
   * 得到选中风场风机集合
   *
   * @type {limitedTurbine[]}@memberof TurbineDataListComponent
   */
  onSelectedDevicesChange(ev: Device[]) {
    this.turbineIds = [];
    this.turbineIds.push(...ev.map(device => device.deviceId))
    if (this.turbineIds.length > 0) {
      this.initEchartsData(this.active);
    } else {
      return;
    }
  }

  public onClickHeader(n: number) {
    this.active = n;
    if (this.active == 2) {//点击年
      this.years = [];
      for (let i = 1; i < 10; i++) {
        this.years.push((new Date().getFullYear() - i).toString())
      }
      this.currentYear = this.years[0]
    } else {
      this.years = [];
      for (let i = 0; i < 10; i++) {
        this.years.push((new Date().getFullYear() - i).toString())
      }
      this.currentYear = new Date().getFullYear().toString();
      this.currentQuarter = Math.floor((new Date().getMonth() % 3 == 0 ? (new Date().getMonth() / 3) : (new Date().getMonth() / 3 + 1))) - 1;
      this.quarters = [];
      for (let k = 1; k <= this.currentQuarter; k++) {
        this.quarters.push(k);
      }
    }
    this.onSearch(this.active)
  }

  public onSearch(active: number) {
    this.initEchartsData(active);

  }

  //获取数据;
  private initEchartsData(active: number) {
    if (active == 0) {//月度
      let month = new Date(this.currentYear + '-' + this.currentMonth)
      this.dateType = 2
      this.originalActualMonth = [];
      this.actualWindPowerDataMonth = [];

      this.originalModelWindPowerMonth = [];
      this.originalPowerLossMonth = [];
      this.powerLossDataMonth = [];
      this.compareDataHighMonth = [];
      this.compareDataLowMonth = [];
      this.actualWindPowerService.getWindPowerData(this.turbineIds, this.dateType, month)
        .then(res => {
          if (!res) {
            return false;
          }
          ;
          //现场数据重复问题
          let oldArr = res.windPowerList;
          let newArr = [];//新数组
          for (var i = 0; i < oldArr.length; i++) {
            var flag = true;
            for (var j = 0; j < newArr.length; j++) {
              if (oldArr[i].wind == newArr[j].wind) {
                flag = false;
              }
              ;
            }
            ;
            if (flag) {
              newArr.push(oldArr[i]);
            }
            ;
          }
          ;
          res.windPowerList = newArr;


          this.windPowersTabData = [];
          //导出的表格逻辑
          res.windPowerList.forEach(windPower => {
            //设计曲线的值
            this.windPowersTabData.push({wind: windPower.wind, power: windPower.power, deviceList: []});
          })
          this.windPowersTabData.forEach(tableDate => {
            //实测风速和功率
            res.actualWindPowerList.forEach(windPower => {
              if (!tableDate.deviceList.find(o => o.deviceName == windPower.deviceName)) {
                tableDate.deviceList.push({deviceName: windPower.deviceName, power: 0})
              }


            })

          })

          this.windPowersTabData.forEach(tableDate => {
            tableDate.deviceList.forEach(device => {
              res.actualWindPowerList.forEach(item => {
                if (item.deviceName == device.deviceName && item.wind == tableDate.wind) {
                  device.power = item.power;
                }
              })
            })
          });


          this.originalActualMonth = [...res.actualWindPowerList];
          this.actualWindPowerDataMonth.push(...this.originalActualMonth);

          //电量耗损数据
          this.originalPowerLossMonth = [...res.powerLossList];
          this.powerLossDataMonth = [...this.originalPowerLossMonth];

          //型号设计曲线数据
          this.originalModelWindPowerMonth = [...res.windPowerList];
          this.modelWindPowerDataMonth = [...this.originalModelWindPowerMonth];

          //型号功率的最大值
          let powers = this.modelWindPowerDataMonth.map(o => o.power);
          this.maxPower = Math.max.apply(Math, powers) + 100;

          //曲线通过高低分组
          this.powerLossDataMonth.forEach(o => {
            if (o.performLossPer > this.compareParamLow) {
              this.compareDataLowMonth.push(o)
            }
            if (o.performLossPer < this.compareParamHigh) {
              this.compareDataHighMonth.push(o)
            }
          })

          //构建风机功率曲线集合
          let list: List<ActualWindPower> = new List(this.actualWindPowerDataMonth);
          //按状态风机id分组
          let groups = list.GroupBy(grouper => grouper.deviceId, mapper => mapper);
          let turbineId = Object.getOwnPropertyNames(groups);        //["14","15","16"];

          let series = [];
          let modelSeriesData = [];
          let legendName = [];
          let actualWindPowerArr: ActualWindPower[] = [];

          // let index = this.modelWindPowerDataMonth.findIndex(o =>o.wind==25);


          this.modelWindPowerDataMonth.forEach(o => {
            modelSeriesData.push([o.wind, o.power])
          })


          series.push({
            name: '设计曲线',
            type: 'line',
            smooth: true,
            data: modelSeriesData,
          })
          legendName.push('设计曲线')

          turbineId.forEach(element => {
            actualWindPowerArr = Object.getOwnPropertyDescriptor(groups, element).value;   //三个数组;
            let seriesData: number[][] = [];

            actualWindPowerArr.forEach(o => {
              seriesData.push([o.wind, o.power]);
            })
            series.push({
              name: actualWindPowerArr[0].deviceName,
              type: 'line',
              smooth: true,
              data: seriesData,
            })

            legendName.push(actualWindPowerArr[0].deviceName);
          })

          this.monthSeries = series;
          this.monthLegend = {
            x: 'right',
            right: '5%',
            align: 'left',
            data: legendName,
            orient: 'vertical',
            y: 50,
            textStyle: {    		//图例文字的样式
              color: '#ffa320',
              fontSize: 14
            }
          }

        })
        .catch(error => {
          if (this.application.appConfigData.isShowErr) {
            this._message.info('获取月度风功率数据' + error, {nzDuration: 3000});
          }
          //console.log("app-power-compare has error", error);
        });

    }
    else if (active == 1) {//季度
      this.originalActualQuarter = [];
      this.actualWindPowerDataQuarter = [];
      this.powerLossDataQuarter = [];
      this.compareDataHighQuarter = [];
      this.compareDataLowQuarter = [];
      this.originalModelWindPowerQuarter = [];
      this.modelWindPowerDataQuarter = [];
      let quarterDate: Date;
      if (this.currentQuarter == 1) {
        quarterDate = new Date(this.currentYear)
      } else if (this.currentQuarter == 2) {
        quarterDate = new Date(this.currentYear + '-' + '4')
      } else if (this.currentQuarter == 3) {
        quarterDate = new Date(this.currentYear + '-' + '7')
      } else {
        quarterDate = new Date(this.currentYear + '-' + '10')
      }
      this.dateType = 4;
      this.actualWindPowerService.getWindPowerData(this.turbineIds, this.dateType, quarterDate)
        .then(res => {
          if (!res) {
            return false;
          }
          ;

          //现场数据重复问题
          let oldArr = res.windPowerList;
          let newArr = [];//新数组
          for (var i = 0; i < oldArr.length; i++) {
            var flag = true;
            for (var j = 0; j < newArr.length; j++) {
              if (oldArr[i].wind == newArr[j].wind) {
                flag = false;
              }
              ;
            }
            ;
            if (flag) {
              newArr.push(oldArr[i]);
            }
            ;
          }
          ;
          res.windPowerList = newArr;


          this.windPowersTabData = [];
          //导出的表格逻辑
          res.windPowerList.forEach(windPower => {
            //设计曲线的值
            this.windPowersTabData.push({wind: windPower.wind, power: windPower.power, deviceList: []});
          })
          this.windPowersTabData.forEach(tableDate => {
            //实测风速和功率
            res.actualWindPowerList.forEach(windPower => {
              if (!tableDate.deviceList.find(o => o.deviceName == windPower.deviceName)) {
                tableDate.deviceList.push({deviceName: windPower.deviceName, power: 0})
              }
            })
          })
          this.windPowersTabData.forEach(tableDate => {
            tableDate.deviceList.forEach(device => {
              res.actualWindPowerList.forEach(item => {
                if (item.deviceName == device.deviceName && item.wind == tableDate.wind) {
                  device.power = item.power;
                }
              })
            })
          });


          this.originalActualQuarter = [...res.actualWindPowerList];
          this.actualWindPowerDataQuarter.push(...this.originalActualQuarter);

          //电量耗损数据
          this.originalPowerLossQuarter = [...res.powerLossList];
          this.powerLossDataQuarter = [...this.originalPowerLossQuarter];

          //型号设计曲线数据
          this.originalModelWindPowerQuarter = [...res.windPowerList];
          this.modelWindPowerDataQuarter = [...this.originalModelWindPowerQuarter]

          //型号功率的最大值
          let powers = this.modelWindPowerDataQuarter.map(o => o.power);
          this.maxPower = Math.max.apply(Math, powers) + 100;

          //曲线通过高低分组
          this.powerLossDataQuarter.forEach(o => {
            if (o.performLossPer > this.compareParamLow) {
              this.compareDataLowQuarter.push(o)
            }
            if (o.performLossPer < this.compareParamHigh) {
              this.compareDataHighQuarter.push(o)
            }
          })

          //构建风机功率曲线集合
          let list: List<ActualWindPower> = new List(this.actualWindPowerDataQuarter);
          //按状态风机id分组
          let groups = list.GroupBy(grouper => grouper.deviceId, mapper => mapper);
          let turbineId = Object.getOwnPropertyNames(groups);        //["14","15","16"];

          let series = [];
          let modelSeriesData = [];
          let actualWindPowerArr: ActualWindPower[] = [];
          let legendName = [];

          this.modelWindPowerDataQuarter.forEach(o => {
            modelSeriesData.push([o.wind, o.power])
          })

          series.push({
            name: '设计曲线',
            type: 'line',
            smooth: true,
            data: modelSeriesData
          })

          legendName.push('设计曲线')

          turbineId.forEach(element => {
            actualWindPowerArr = Object.getOwnPropertyDescriptor(groups, element).value;   //三个数组;
            let seriesData: number[][] = [];
            actualWindPowerArr.forEach(o => {
              seriesData.push([o.wind, o.power])
            })
            series.push({
              name: actualWindPowerArr[0].deviceName,
              type: 'line',
              smooth: true,
              data: seriesData,
            })

            legendName.push(actualWindPowerArr[0].deviceName);
          })

          this.quarterSeries = series;
          this.quarterLegend = {
            x: 'right',
            right: '5%',
            align: 'left',
            data: legendName,
            orient: 'vertical',
            y: 50,
            textStyle: {    		//图例文字的样式
              color: '#ffa320',
              fontSize: 14
            }
          }
        })
        .catch(error => {
          if (this.application.appConfigData.isShowErr) {
            this._message.info('获取季度风功率数据' + error, {nzDuration: 3000});
          }

          //console.log("app-power-compare has error", error);
        });
    }
    else {//年
      let year = new Date(this.currentYear);
      this.dateType = 3;
      this.actualWindPowerService.getWindPowerData(this.turbineIds, this.dateType, year)
        .then(res => {
          if (!res) {
            return false;
          }
          ;

          //现场数据重复问题
          let oldArr = res.windPowerList;
          let newArr = [];//新数组
          for (var i = 0; i < oldArr.length; i++) {
            var flag = true;
            for (var j = 0; j < newArr.length; j++) {
              if (oldArr[i].wind == newArr[j].wind) {
                flag = false;
              }
              ;
            }
            ;
            if (flag) {
              newArr.push(oldArr[i]);
            }
            ;
          }
          ;

          res.windPowerList = newArr;


          this.windPowersTabData = [];
          //导出的表格逻辑
          res.windPowerList.forEach(windPower => {
            //设计曲线的值
            this.windPowersTabData.push({wind: windPower.wind, power: windPower.power, deviceList: []});
          })
          this.windPowersTabData.forEach(tableDate => {
            //实测风速和功率
            res.actualWindPowerList.forEach(windPower => {
              if (!tableDate.deviceList.find(o => o.deviceName == windPower.deviceName)) {
                tableDate.deviceList.push({deviceName: windPower.deviceName, power: 0})
              }
            })
          })
          this.windPowersTabData.forEach(tableDate => {
            tableDate.deviceList.forEach(device => {
              res.actualWindPowerList.forEach(item => {
                if (item.deviceName == device.deviceName && item.wind == tableDate.wind) {
                  device.power = item.power;
                }
              })
            })
          });


          this.originalActualYear = [];
          this.actualWindPowerDataYear = [];
          this.powerLossDataYear = [];
          this.originalPowerLossYear = [];
          this.compareDataHighYear = [];
          this.compareDataLowYear = [];
          this.modelWindPowerData = [];

          // 风机功率曲线数据
          this.originalActualYear = [...res.actualWindPowerList];
          this.actualWindPowerDataYear.push(...this.originalActualYear);

          // 电量耗损数据
          this.originalPowerLossYear = [...res.powerLossList];
          this.powerLossDataYear = [...this.originalPowerLossYear];

          // 型号设计曲线数据
          this.originalModelWindPower = [...res.windPowerList];
          this.modelWindPowerData = [...this.originalModelWindPower];

          // 型号功率的最大值
          let powers = this.modelWindPowerData.map(o => o.power);
          this.maxPower = Math.max.apply(Math, powers) + 100;

          // 曲线通过高低分组
          this.powerLossDataYear.forEach(o => {
            if (o.performLossPer > this.compareParamLow) {
              this.compareDataLowYear.push(o)
            }
            if (o.performLossPer < this.compareParamHigh) {
              this.compareDataHighYear.push(o)
            }
          })

          //构建风机功率曲线集合
          let list: List<ActualWindPower> = new List(this.actualWindPowerDataYear);
          //按状态风机id分组
          let groups = list.GroupBy(grouper => grouper.deviceId, mapper => mapper);
          let turbineId = Object.getOwnPropertyNames(groups);        //["14","15","16"];

          let series = [];
          let modelSeriesData: number[][] = [];
          let actualWindPowerArr: ActualWindPower[] = []
          let legendName = [];

          this.modelWindPowerData.forEach(o => {
            modelSeriesData.push([o.wind, o.power])
          })

          series.push({
            name: '设计曲线',
            type: 'line',
            smooth: true,
            data: modelSeriesData,
          })

          legendName.push('设计曲线')

          turbineId.forEach(element => {
            actualWindPowerArr = Object.getOwnPropertyDescriptor(groups, element).value;   //三个数组;
            let seriesData: number[][] = [];

            actualWindPowerArr.forEach(o => {
              seriesData.push([o.wind, o.power])
            })
            series.push({
              name: actualWindPowerArr[0].deviceName,
              type: 'line',
              smooth: true,
              data: seriesData,
            })

            legendName.push(actualWindPowerArr[0].deviceName)
          })

          this.yearSeries = series;
          this.yearLegend = {
            x: 'right',
            right: '5%',
            align: 'left',
            data: legendName,
            orient: 'vertical',
            y: 50,
            textStyle: {    		//图例文字的样式
              color: '#ffa320',
              fontSize: 14
            }
          }
        })
        .catch(error => {
          if (this.application.appConfigData.isShowErr) {
            this._message.info('获取年度风功率数据' + error, {nzDuration: 3000});
          }

          //console.log("app-power-compare has error", error);
        });

    }

  }

  exportData(index) {
    // 使用outerHTML属性获取整个table元素的HTML代码（包括<table>标签），然后包装成一个完整的HTML文档，设置charset为urf-8以防止中文乱码
    var html = '';
    if (index == 0) {//月度
      html = '<html><head><meta charset=\'utf-8\' /></head><body>' + document.getElementById('ex-tab-month').outerHTML + '</body></html>';
    } else if (index == 1) {//季度
      html = '<html><head><meta charset=\'utf-8\' /></head><body>' + document.getElementById('ex-tab-quarter').outerHTML + '</body></html>';
    } else {//年度
      html = '<html><head><meta charset=\'utf-8\' /></head><body>' + document.getElementById('ex-tab-year').outerHTML + '</body></html>';
    }

    // 实例化一个Blob对象，其构造函数的第一个参数是包含文件内容的数组，第二个参数是包含文件类型属性的对象
    var blob = new Blob([html], {type: 'application/vnd.ms-excel'});
    // var a = document.getElementsByTagName("a")[0];
    // 利用URL.createObjectURL()方法为a元素生成blob URL
    var href = URL.createObjectURL(blob);
    document.getElementById('ex').setAttribute('href', href);

    // // 设置文件名，目前只有Chrome和FireFox支持此属性
    document.getElementById('ex').setAttribute('download', '功率曲线比较.xls');
    // a.download = "实际功率曲线.xls";
    // a.click();
    // document.getElementById("ex").click();

  }

}


// WEBPACK FOOTER //
// ./src/app/module/performance/power-compare/power-compare.component.ts
